package com.yb.xczx.cloud.passport.config;

import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.redis.RedisDataSource;
import com.alibaba.csp.sentinel.datasource.redis.config.RedisConnectionConfig;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/25 16:55
 * FileName: SentinelConfig
 * Description:
 */

@Configuration
public class SentinelConfig {

    @Bean
    public ReadableDataSource readableDataSource(){
        RedisConnectionConfig config = RedisConnectionConfig.builder()
                .withHost("redis")
                .withPort(6379)
                .withDatabase(2)
                .build();

        ObjectMapper objectMapper = new ObjectMapper();
        JsonConverter<FlowRule> jsonConverter = new JsonConverter<>(objectMapper,FlowRule.class);
        ReadableDataSource<String,List<FlowRule>> redisDataSource = new RedisDataSource<List<FlowRule>>(config, "xczx:sentinel:passport", "xczx:sentinel:passport", jsonConverter);
        FlowRuleManager.register2Property(redisDataSource.getProperty());
        return  redisDataSource;
    }
}
